const secretKey = "secretKey"
import { AsyncRouter, roleList, User, userList, userRoleList } from "./db";

const tokenKey = "Authorization"
// 生成token
export const generateToken = (userId: string) => {
  return {
    token: secretKey + "token-" + userId,
    tokenKey
  }
}

// 解析token
export const decodeToken = (token: string) => {
  if (!token.startsWith(secretKey)) {
    return {
      valid: false,
    }
  }
  const userId = token.split("-")[1]
  return {
    valid: true,
    userId,
  }
}


interface UserInfo {
  token?: string,
  userInfo?: User,
  valid: boolean,
  tokenKey?: string
}

// 验证用户账号密码
export const checkUser = (user: User): UserInfo => {
  const { username, password } = user
  const userInfo = userList.find((item) => {
    if (item.username === username && item.password === password) {
      return true
    }
  })
  if (userInfo) {
    return {
      ...generateToken(userInfo.id as string),
      userInfo,
      valid: true,
    }
  } else {
    return {
      valid: false,
    }
  }
}


// 生成角色路由
export const generateRoleRouter = (userId: any) => {
  const roleId = userRoleList.find((item) => {
    if (item.userId === userId) {
      return true
    }
  })?.roleId
  const roleData = roleList.find((item) => {
    return item.id === roleId
  })
  const role = roleData?.role
  const getMenuFun = (menuList: any[]) => {
    return menuList.reduce((pre, item: any) => {
      const hasPermission = item.meta.roles.includes(role)
      // console.log(hasPermission);
      let menuItem: any = item
      if (hasPermission) {
        if (item?.children && item?.children.length > 0) {
          menuItem.children = getMenuFun(item.children)
        }
      }
      return hasPermission ? [...pre, menuItem] : pre
    }, [])
  }
  return getMenuFun(AsyncRouter)
}